package com.gin.kotlin.no_gay_alliance.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.view.MenuProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.argument.UserCenterArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.ActivityUserCenterBinding
import com.gin.kotlin.no_gay_alliance.fragment.main.usercenter.AbstractUserCenterTabFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.usercenter.UserCenterTabBaseInfoFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.usercenter.UserCenterTabIpLocationFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.usercenter.UserCenterTabSignatureFragment
import com.gin.kotlin.no_gay_alliance.model.UserDetailModel
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.UserInfoProvider
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils.Companion.TIME_ONLY_FORMATTER
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import java.time.ZoneId

/**
 * 用户中心活动，底部为数据版本，包含模块：
 * *  基础信息
 * *  额外信息：管理的版面，个人版面，荣誉，声望，buff，备注，徽章
 * *  签名
 * @property argument UserCenterArgument
 */
class UserCenterActivity : AbstractBindingActivity<ActivityUserCenterBinding>(), RCallback<UserDetailModel, UserCenterArgument>, TabLayoutMediator.TabConfigurationStrategy {

    private var userDetail: UserDetailModel? = null
    private var tabLayoutMediator: TabLayoutMediator? = null
    private lateinit var argument: UserCenterArgument
    private lateinit var fragmentStateContainers: List<FragmentStateContainer>
    var currentFragment: AbstractUserCenterTabFragment<*>? = null
        set(value) {
            field = value
            supportInvalidateOptionsMenu()
        }

    /**
     * onCreate方法的后续操作，如 [AbstractBindingActivity.registerLauncher]， 或 [AbstractBindingActivity.attachTabLayout]
     */
    override fun onCreate() {

        this.fragmentStateContainers = listOf(
            FragmentStateContainer("基础信息", 1) { UserCenterTabBaseInfoFragment(userDetail) },
            FragmentStateContainer("签名", 2) { UserCenterTabSignatureFragment(userDetail) },
            FragmentStateContainer("IP轨迹", 3) { UserCenterTabIpLocationFragment(userDetail) },
        )
        request()
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        menu?.let { (currentFragment as? MenuProvider)?.onPrepareMenu(it) }
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
        tab.text = fragmentStateContainers[position].title
    }

    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        //清空菜单
        menu.clear()

        //先装载当前Fragment的菜单
        (currentFragment as? MenuProvider)?.onCreateMenu(menu, menuInflater)

        menuInflater.inflate(R.menu.refresh, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 先由Fragment处理
        if ((currentFragment as? MenuProvider)?.onMenuItemSelected(item) == true) {
            return true
        }

        when (item.itemId) {
            R.id.mi_refresh -> {
                refresh()
                return true
            }
        }

        return super.onOptionsItemSelected(item)
    }

    /**
     * 解析意图
     * @param intent Intent?
     */
    override fun handleIntent(intent: Intent) {
        this.argument = parseArgument(intent, KEY_ARGUMENT, UserCenterArgument::class.java) { UserCenterArgument.parseUrl(it) }
    }

    fun refresh() {
        Log.i(TAG, "刷新: ${mapper.writeValueAsString(this.argument)}")
        request(true)
    }

    /**
     *发送请求
     * @param ignoreCache Boolean
     */

    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.tvWarning.visibility = View.GONE
        b.tvTimestamp.visibility = View.GONE
        UserInfoProvider.getInstance().enqueue(this.argument, ignoreCache = ignoreCache, callback = this)
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onSuccess(data: UserDetailModel, ignoreCache: Boolean) {
        // 替换数据
        this.userDetail = data

        val b = this.b ?: return
        ui {
            // 为ViewPager2设置适配器
            b.viewPager2.adapter = object : FragmentStateAdapter(this) {
                override fun getItemCount() = fragmentStateContainers.size
                override fun createFragment(position: Int) = FragmentStateContainer.newInstance(fragmentStateContainers, position)
            }
            this.tabLayoutMediator = if (this.tabLayoutMediator == null) attachTabLayout(b.tabLayout, b.viewPager2, this) else this.tabLayoutMediator


            b.tvWarning.visibility = View.GONE
            b.tabLayout.visibility = View.VISIBLE
            b.tvTimestamp.visibility = View.VISIBLE
            b.viewPager2.visibility = View.VISIBLE
            b.tvTimestamp.text = getString(R.string.tv_timestamp, TIME_ONLY_FORMATTER.format(data.timestamp.withZoneSameInstant(ZoneId.systemDefault())))
            data.username?.also { setToolbarTitle(it) }
        }

    }

    override fun onError(errorMessage: String) {
        // 如果不是html，尝试使用html
        if (!argument.html) {
            onFailed(true, argument)
            return
        }

        val b = this.b ?: return
        ui {
            b.tvWarning.visibility = View.VISIBLE
            b.tabLayout.visibility = View.GONE
            b.tvTimestamp.visibility = View.GONE
            b.viewPager2.visibility = View.GONE
            b.tvWarning.text = errorMessage
        }
    }

    override fun onFailed(ignoreCache: Boolean, params: UserCenterArgument?) {
        argument = argument.copy(html = true)
        Log.i(TAG, "使用HTML模式请求: ${mapper.writeValueAsString(argument)}")
        UserInfoProvider.getInstance().enqueue(argument, ignoreCache = ignoreCache, callback = this)
    }

    companion object {
        const val KEY_ARGUMENT = "ARGUMENT_USER_CENTER"

        /**
         * 使用URL启动活动
         * @param context Context
         * @param url String
         */
        fun startActivity(context: Context, url: String) {
            context.startActivity(Intent(context, UserCenterActivity::class.java).also { it.setData(Uri.parse(url)) })
        }

        /**
         * 使用用户ID或用户名启动活动
         * @param context Context
         * @param userId Long?
         * @param username String?
         */
        fun startActivity(context: Context, userId: Long? = null, username: String? = null) {
            // 如果id小于1，不启动
            if (userId != null && userId < 1) return
            startActivity(context, UserCenterArgument(userId, username))
        }

        /**
         * 使用参数启动活动
         * @param context Context
         * @param argument UserCenterArgument
         */
        fun startActivity(context: Context, argument: UserCenterArgument) {
            context.startActivity(Intent(context, UserCenterActivity::class.java).also { it.putExtra(KEY_ARGUMENT, argument) })
        }

    }
}
